import React, {useState, useEffect} from 'react';
import {Panel} from '../../../components/Index';
import {Button, Card, Form, Input, Table, Space, Avatar, Modal, message} from 'antd';
import {connect} from 'react-redux';
import ModalForm from './ModalForm';
import axios from "axios";
import {PlusOutlined} from '@ant-design/icons';
import RelateModalForm from "./RelateModalForm";
import {get, post} from "../../../service";
function User(props) {
    const [list, setList] = useState([]); //列表展示
    const [pagination, setPagination] = useState({}); //分页
    const [form] = Form.useForm();  // Antd 的 Form 实例
    const [filter, setFilter] = useState({}); // 过滤条件

    useEffect(() => {
        onGetList();  // 获取用户列表
    }, []);

    const {modalForm,relateModalForm} = props.userState;

    // 获取用户列表
    const onGetList = (params) => {
        get('/api/user/list', {params}).then(res => {
            setList(res.records);
            setPagination(res.pagination);
        });
    };

    // 搜索功能
    const onSearch = (values) => {
        onGetList(values);  // 根据搜索条件获取列表
        setFilter(values);  // 更新过滤条件
    };
    // 获取表格配置
    const getTableProps = () => ({
        onChange: (pagination) => {
            //传入分页信息，过滤条件
            onGetList({...pagination, ...filter});
        },
        //分页器
        pagination: {
            ...pagination,
            showTotal: total => `共 ${total} 条`,
        },
        columns: [
            {
                title: '用户名',
                dataIndex: 'name',
                render: (text, record) => {
                    return (
                        <Space>
                            <Avatar src={record.picture}/>
                            {text}
                        </Space>
                    );
                }
            },
            {title: '账户', dataIndex: 'account'},
            {title: '联系方式', dataIndex: 'tel'},
            {title: '邮箱', dataIndex: 'email'},
            {
                title: '操作',
                render: (record) => {
                    return (
                        <Space>
                            <a onClick={oView(record)}>查看</a>
                            <a onClick={onEdit(record)}>编辑</a>
                            <a onClick={onRemove(record)}>删除</a>
                            <a onClick={onRelateMenu(record)}>关联菜单</a>
                        </Space>
                    );
                }
            }
        ],
        dataSource: list,
    });

    // 新增用户
    const OnAdd = () => {
        props.dispatch({
            type: 'showModalForm',
            data: {
                title: '新增',
                data: {},
                refreshList: onGetList
            }
        });
    };
    //查看详请
    const oView = (record) => {
        return () => {
            props.dispatch({
                type: 'showModalForm',
                data: {
                    title: '详请',
                    data: {...record,area:record.area.split(',')},
                }
            })
        }
    }
    // 删除用户
    const onRemove = (record) => {
        return () => {
            Modal.confirm({
                title: '删除',
                content: '确定要删除吗？',
                onOk: async () => {
                    try {
                        await post('/api/user/delete', { id: record.id });
                        message.success("删除成功");
                        onGetList();
                    } catch (error) {
                        message.error("删除失败");
                    }
                }
            });
        };
    };
    // 重置表单功能
    const onReset = () => {
        form.resetFields();  // 清空表单并恢复初始状态
        onGetList();         // 重置后重新获取完整用户列表
    };
    // 编辑用户
    const onEdit = (record) => {
        return () => {
            props.dispatch({
                type: 'showModalForm',
                data: {
                    title: '编辑',
                    data: {...record,area:record.area.split(',')},
                    refreshList: onGetList
                }
            })
        }
    }
    //关联菜单
   const onRelateMenu= (record) => {
        return ()=>{
            props.dispatch({
                type:'showRelateModalForm',
                data:{
                    title:'配置菜单',
                    data:record,
                    refreshList: onGetList
                }
            })
        }
   }
    return (
        <Panel title="用户管理">
            <Card className='m-filter'>
                <Form layout="inline" form={form} onFinish={onSearch}>
                    <Form.Item label="用户名" name="name">
                        <Input/>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                    <Form.Item>
                        <Button onClick={onReset}>重置</Button>
                    </Form.Item>
                </Form>
            </Card>
            <Card>
                <div className="m-operate">
                    <Button type="primary" icon={<PlusOutlined/>} onClick={OnAdd}>新增</Button>
                </div>
                <Table {...getTableProps()} />
            </Card>
            {modalForm && <ModalForm {...modalForm} {...props} />}
            {relateModalForm && <RelateModalForm {...relateModalForm} {...props} />}
        </Panel>
    );
}

const mapStateToProps = (store) => ({userState: store.user});
const mapDispatchToProps = (dispatch) => ({
    dispatch
});
export default connect(mapStateToProps, mapDispatchToProps)(User);
